from django import http
from django.utils.deprecation import MiddlewareMixin                                                                                                                                                                 
try:
    from django.conf import settings
    XS_SHARING_ALLOWED_ORIGINS = settings.XS_SHARING_ALLOWED_ORIGINS
    XS_SHARING_ALLOWED_METHODS = settings.XS_SHARING_ALLOWED_METHODS
    XS_SHARING_ALLOWED_HEADERS = settings.XS_SHARING_ALLOWED_HEADERS
    XS_SHARING_ALLOWED_CREDENTIALS = settings.XS_SHARING_ALLOWED_CREDENTIALS
except AttributeError:
    XS_SHARING_ALLOWED_ORIGINS = '*'
    #XS_SHARING_ALLOWED_METHODS = ['POST', 'GET', 'OPTIONS', 'PUT', 'DELETE']
    XS_SHARING_ALLOWED_METHODS = ['POST', 'GET']
    XS_SHARING_ALLOWED_HEADERS = ['Content-Type', '*']
    XS_SHARING_ALLOWED_CREDENTIALS = 'true'
                                                                                                                                                                  
                                                                                                                                                                  
class Cors(MiddlewareMixin):
    """
    This middleware allows cross-domain XHR using the html5 postMessage API.
                                                                                                                                                                      
    Access-Control-Allow-Origin: http://foo.example
    Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE
                                                                                                                                                                  
    Based off https://gist.github.com/426829
    """
    def process_request(self, request):
        if 'HTTP_ACCESS_CONTROL_REQUEST_METHOD' in request.META:
            response = http.HttpResponse()
            response['Access-Control-Allow-Origin']  = XS_SHARING_ALLOWED_ORIGINS
            response['Access-Control-Allow-Methods'] = ",".join( XS_SHARING_ALLOWED_METHODS )
            response['Access-Control-Allow-Headers'] = ",".join( XS_SHARING_ALLOWED_HEADERS )
            response['Access-Control-Allow-Credentials'] = XS_SHARING_ALLOWED_CREDENTIALS
            return response
                                                                                                                                                                  
        return None
                                                                                                                                                                  
    def process_response(self, request, response):
        response['Access-Control-Allow-Origin']  = XS_SHARING_ALLOWED_ORIGINS
        response['Access-Control-Allow-Methods'] = ",".join( XS_SHARING_ALLOWED_METHODS )
        response['Access-Control-Allow-Headers'] = ",".join( XS_SHARING_ALLOWED_HEADERS )
        response['Access-Control-Allow-Credentials'] = XS_SHARING_ALLOWED_CREDENTIALS
                                                                                                                                                                  
        return response


class MyAuthMiddleware(MiddlewareMixin):
    def process_request(self,request):
        path =request.path_info
        # print('weburl:',path[1:-1])
        permission_dic = request.session.get(settings.PERMISSION_SESSION_KEY)
        # print(permission_dic)
        flag =False
        if path=='/login/':
            return None
        path = path[1:-1]
        for reg in permission_dic.values():
            for url in reg['urls']:
                url='^%s$'%(url[1:-1])
                # print(path)
                print(url)
                if re.findall(url,path):
                    flag=True
                    break
        if flag:
            return None
        else:
            return HttpResponse("无访问权限")

class ExceptionTestMiddleware(MiddlewareMixin):
    # 如果注册多个process_exception函数，那么函数的执行顺序与注册的顺序相反。(其他中间件函数与注册顺序一致)
    # 中间件函数，用到哪个就写哪个，不需要写所有的中间件函数。
    def process_exception(self, request, exception):
        '''视图函数发生异常时调用'''
        print(request,exception)
        return JsonResponse({'error':exception},status=403)
